package com.me.common.util;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 解密 navicat 导出的数据库连接密码
 */
public class NavicatPasswordUtil {
    private int version;
    private static final String AES_KEY = "libcckeylibcckey";
    private static final String AES_IV = "libcciv libcciv ";
    private static final String BLOW_STRING = "3DC5CA39";
    private byte[] blowKey;
    private byte[] blowIv;

    public static void main(String[] args) throws Exception {
        //需要指定版本两种，11或12
        //NavicatPassword navicatPassword = new NavicatPassword(11);
        NavicatPasswordUtil navicatPassword = new NavicatPasswordUtil(12);

        //解密
        String decode = navicatPassword.decrypt("4C3FD05336C6BC014FB13D48AECCFCE44C98219BD8AC88C68A4ACA90BB577050");
        System.out.println(decode);
    }

    public NavicatPasswordUtil(int version) throws NoSuchAlgorithmException {
        this.version = version;
        this.blowKey = sha1("3DC5CA39");
        this.blowIv = hexStringToByteArray("d9c7c3c8870d64bd");
    }

    public String encrypt(String string) throws Exception {
        switch (version) {
            case 11:
                return encryptEleven(string);
            case 12:
                return encryptTwelve(string);
            default:
                return null;
        }
    }

    private String encryptEleven(String string) throws Exception {
        int round = string.length() / 8;
        int leftLength = string.length() % 8;
        StringBuilder result = new StringBuilder();
        byte[] currentVector = blowIv;

        for (int i = 0; i < round; i++) {
            byte[] block = xorBytes(string.substring(8 * i, 8 * (i + 1)).getBytes(), currentVector);
            byte[] temp = encryptBlock(block);
            currentVector = xorBytes(currentVector, temp);
            result.append(bytesToHex(temp));
        }

        if (leftLength > 0) {
            currentVector = encryptBlock(currentVector);
            result.append(bytesToHex(xorBytes(string.substring(8 * round).getBytes(), currentVector)));
        }

        return result.toString().toUpperCase();
    }

    private byte[] encryptBlock(byte[] block) throws Exception {
        Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
        SecretKey secretKey = new SecretKeySpec(blowKey, "Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(block);
    }

    private byte[] decryptBlock(byte[] block) throws Exception {
        Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
        SecretKey secretKey = new SecretKeySpec(blowKey, "Blowfish");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(block);
    }

    private byte[] xorBytes(byte[] str1, byte[] str2) {
        byte[] result = new byte[str1.length];
        for (int i = 0; i < str1.length; i++) {
            result[i] = (byte) (str1[i] ^ str2[i]);
        }
        return result;
    }

    private String encryptTwelve(String string) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKey = new SecretKeySpec(AES_KEY.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(AES_IV.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] encrypted = cipher.doFinal(string.getBytes());
        return bytesToHex(encrypted).toUpperCase();
    }

    public String decrypt(String string) throws Exception {
        switch (version) {
            case 11:
                return decryptEleven(string);
            case 12:
                return decryptTwelve(string);
            default:
                return null;
        }
    }

    private String decryptEleven(String upperString) throws Exception {
        byte[] string = hexStringToByteArray(upperString.toLowerCase());

        int round = string.length / 8;
        int leftLength = string.length % 8;
        StringBuilder result = new StringBuilder();
        byte[] currentVector = blowIv;

        for (int i = 0; i < round; i++) {
            byte[] encryptedBlock = Arrays.copyOfRange(string, 8 * i, 8 * (i + 1));
            byte[] temp = xorBytes(decryptBlock(encryptedBlock), currentVector);
            currentVector = xorBytes(currentVector, encryptedBlock);
            result.append(new String(temp, StandardCharsets.UTF_8));
        }

        if (leftLength > 0) {
            currentVector = encryptBlock(currentVector);
            result.append(new String(xorBytes(Arrays.copyOfRange(string, 8 * round, string.length), currentVector), StandardCharsets.UTF_8));
        }

        return result.toString();
    }

    private String decryptTwelve(String upperString) throws Exception {
        byte[] string = hexStringToByteArray(upperString.toLowerCase());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKey = new SecretKeySpec(AES_KEY.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(AES_IV.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] decrypted = cipher.doFinal(string);
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    private static byte[] sha1(String input) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        return messageDigest.digest(input.getBytes(StandardCharsets.UTF_8));
    }

    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

